package com.zy.composeworld.base.adapter

import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.zy.activity.bean.BaseViewBindingItemBean
import com.zy.composeworld.ktx.singleClick

class BaseViewBindingItemAdapter(
    private val viewBindingClass: Class<out ViewBinding>,
    private var dataList: List<BaseViewBindingItemBean>
) :
    RecyclerView.Adapter<BaseViewBindingItemAdapter.BaseViewBindingViewHolder>() {

    override fun onCreateViewHolder(
        viewGroup: ViewGroup,
        type: Int
    ): BaseViewBindingViewHolder {
        val viewBinding = viewBindingClass.getMethod("inflate", LayoutInflater::class.java)
            .invoke(null, LayoutInflater.from(viewGroup.context)) as ViewBinding
        return BaseViewBindingViewHolder(viewBinding)
    }

    override fun onBindViewHolder(viewHolder: BaseViewBindingViewHolder, position: Int) {
        viewHolder.bind(dataList[position])
    }

    fun setNewData(newDataList: List<BaseViewBindingItemBean>?) {
        newDataList?.let {
            dataList = it
            notifyDataSetChanged()
        }
    }


    override fun getItemCount(): Int {
        return dataList.size
    }

    inner class BaseViewBindingViewHolder(val binding: ViewBinding) :
        RecyclerView.ViewHolder(binding.root) {
        private var bean: BaseViewBindingItemBean? = null

        init {
            binding.root.singleClick { v ->
                bean?.click?.invoke(binding)
            }
        }

        fun bind(bean: BaseViewBindingItemBean?) {
            this.bean = bean
            bean ?: return
            //初始化
            bean.initData.invoke(binding)
        }
    }
}